#!/bin/sh

usage () {
	cat <<EOF>&2
Usage: ${0##*/} FOLDERS

Sort media files in FOLDERS by duration.

EOF
}

[ $# -eq 0 ] && usage && exit 1
[ "$1" = "-h" ] && usage && exit
[ "$1" = "--" ] && shift

for i; do
	find "$i" -type f -exec mediainfo {} +
done | awk '/^General$/ {while($1!="Complete") getline; gsub(/^[^:]*: /,""); path=$0; while($0!="") {if($1=="Duration"){gsub(/^[^:]*: /,""); duration=$0; time=0; for(i=1;i<=NF;i+=2){if($(i+1)=="h") time+=$i*3600; if($(i+1)=="min") time+=$i*60; if($(i+1)=="s") time+=$i }; printf "%s %s '"'"'%s'"'"'\n", time, duration, path; break} else {getline}}}' | sort -n
